﻿<script type="text/javascript">
    ///<reference path="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js" />
    ///<reference path="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js" />
    ///<reference path="js/lib.js" />



    var _regexButtons =
            [
                {
                    label: "Start of Line",
                    piece: "^"
                },
                {
                    label: "Range",
                    piece: "[_PH_]",
                    prompt: true
                },
                {
                    label: "Any Character",
                    piece: "."
                },
                {
                    label: "One or More Times",
                    piece: "+"
                },
                {
                    label: "Zero or more times",
                    piece: "*"
                },
                 {
                     label: "Exactly {x} Times",
                     piece: "{_PH_}",
                     prompt: true
                 },
                 {
                     label: "Custom Text",
                     piece: "_PH_",
                     prompt: true
                 },
                {
                    label: "End of Line",
                    piece: "$"
                },
               
            ];

    $(document).ready(function () {
        // LocalInit();

        $("#TestResults, #ExistingFilters").jsontable();
        $("#DataSetSelect").change(UpdateExistingFilters);

        PrepRegexBuilderButtons();

        $("#RegexBuilderWorkspace").sortable(
            {
                update: UpdateRegexFieldFromWorkspace,
                tolerence: "pointer",
                
                revert: true,
                forcePlaceholderSize: true,
                //containment: "parent",
                opacity: 0.5,
                tolerance: "pointer",
            }).disableSelection();

        GetJsonSproc("usp_GetDataSets",

           function (json) {

               var sel = $("#DataSetSelect");
               sel.empty();

               $.each(json, function (key, value) {
                   console.dir(value);
                   var o = $("<option>").text(value.Name).val(value.ID);
                   sel.append(o);
               });


               UpdateExistingFilters();
           });

    }
    );


    function TestSqlFilter() {
        var regexString = $("#regexFilter").val();
       // if (regexString == "") regexString = null;

        var dataSetId = $("#DataSetSelect > option:selected").val();
        //console.log("data set id: " + dataSetId)

        var params = {
            DataSetId: dataSetId,
            MorphologyRegex: encodeURIComponent(regexString)
        }
       // if (regexString != null)
         //   params.filter = regexString;

        var limit = $("#limit").val();
        
        if (limit != "")
            params.limit = limit;
        else
            params.limit = 100;

        GetJsonSproc("testfilter",
           params,
            function (json) {
                // console.dir(json);

                var matches = json[1];
                Growl("Matches found for '" + regexString + "' were " + matches);
                //$("#PreviewMatchesCount").text(" (" + json.Table1[0].Matches + " matches)");
                $("#TestResults").jsontable("option",
                    {
                        
                        source: json[0],
                        columnOrder: ["GalaxyName", "Morphology"]
                    });
            });
    }

    function getMatcingGalaxies(data, filter) {
        var arr = [];
        //  console.dir(data);
        for (var i = 0; i < data.length; i++) {
            var galaxy = data[i];

            if (galaxy.Morphology.match(filter)) {
                //  console.log(galaxy.Morphology + " matches filter " + filter.name + "; " + filter.regex);
                arr.push(galaxy);
            }
        }
        return arr;
    }
/*
    function TestRegexFilter() {
        var dataSetId = $("#DataSetSelect > option:selected").val();

        GetJsonSproc("usp_GetObjectsForPlot",
           {
               DataSetId: dataSetId
           },
           function (json) {

               var matches = getMatcingGalaxies(json, $("#regexFilter").val());

               var subset = matches.slice(0, 20);

               $("#TestResults").jsontable("option",
                   {
                       source: subset
                   });
               //console.dir(matches);

           });
    }*/

    function trySave() {
        var sheet = $("#AddWorksheet");

        var name = $("#name").val();
       // var sqlFilter = $("#sqlFilter").val();
        var regexFilter = $("#regexFilter").val();
         
        if (name == "" ) //|| /*sqlFilter == "" ||*/ regexFilter == "")
            return;

        var dataSetId = $("#DataSetSelect > option:selected").val();

        GetJsonSproc("usp_AddMorphologyFilter",
            {
                Name: name,
              //  SqlFilter: sqlFilter,
                RegexFilter: regexFilter,
                DataSetId: dataSetId
            },
            function (json) {
                UpdateExistingFilters();
                Growl("New filter added.");
            });


    }


    function UpdateExistingFilters() {
        var dataSetId = $("#DataSetSelect > option:selected").val();

        GetJsonSproc("usp_GetMorphologyFilters",
            {
                DataSetId: dataSetId
            },
            function (json) {
                $("#ExistingFilters").jsontable("option", "source", json);
            });
    }


    function RegexBuilderButtonClick()
    {
        var btn = $(this);
        var promptText = "";
        var b = _regexButtons[btn.data("index")];
        var s;
        if (typeof b.prompt != "undefined" && b.prompt)
        {
            promptText = prompt("Enter The value for " + btn.text());
            s = b.piece.replace("_PH_", promptText);
        }
        else
            s = b.piece;

        var newBtn = btn.clone();

        newBtn.data("piece", s);
        newBtn.text(b.label + " ( " + s + " )");
        var icon = $("<i class='fa fa-times-circle ml'></i>");
        icon.click(function (e)
        {
            e.preventDefault();
            e.stopPropagation();

            var i = $(this);
            var btn = i.parent();

            btn.remove();
            UpdateRegexFieldFromWorkspace();


        });

        newBtn.append(icon);
       
        newBtn.appendTo($("#RegexBuilderWorkspace"));
      
        //   alert(s);

        UpdateRegexFieldFromWorkspace();
        
    }

    function PrepRegexBuilderButtons()
    {
        

        var buttonBox = $("#RegexBuilderButtons");
        $.each(_regexButtons, function (index, b)
            {
            
            var btn = $("<span class='button'>");
            var p = new String(b.piece);

                btn.text(b.label + " (" + p.replace("_PH_","") + ")");
                btn.data("index", index);
                btn.click(RegexBuilderButtonClick);
                

                btn.appendTo(buttonBox);
            });

    }

    function ResetBuilderWorkspace()
    {
        $("#RegexBuilderWorkspace").empty();
        UpdateRegexFieldFromWorkspace();
    }

    function UpdateRegexFieldFromWorkspace()
    {
        var s = "";
        $("#RegexBuilderWorkspace > .button").each(function (index)
        {
            s += $(this).data("piece");
        });
        
        $("#regexFilter").val(s);
    }


</script>



<div id="AddWorksheet" class="ui-widget  mr" style="min-width:800px;">
    <div class="ui-widget-header">Morphology Filters</div>
    <div class="ui-widget-content pad">
        <div>
            Data Set: <select id="DataSetSelect"></select>
        </div>
        <div>
            Morph. Name
            <input type="text" id="name" />
        </div>
        <div class="ui-widget mt">
            <div class="ui-widget-header">Regex</div>
            <div class="ui-widget-content pad">

            <div class="ui-state-highlight pad mb">Use the buttons below to add and sort pieces of the regular expression. 
                Manual edits to the text field are are overwritten by the buttons. 

                Detailed information on regular expressions is available at <a target="_blank" href="http://www.regularexpressions.info">RegularExpressions.info</a>
                </div>

                <div id="RegexBuilderButtons" class="mt mb">
                    
                </div>

                <div id="RegexBuilderWorkspace" class="mt pad ui-widget-content" style=""></div>
                <div class="clear">
                    Built Regex: <input id="regexFilter" type="text" placeholder="Regex" /> 
                    <span class="button" data-icon="fa fa-undo" onclick="ResetBuilderWorkspace();"> Reset</span>
                    <span class="button" data-icon="fa-save" onclick="trySave();">Add This Morphology Filter</span>
                 </div>
                <div>
                    <input type="number" id="limit" style='width: 5em;' placeholder="limit 100" />
                    <span class="button" data-icon="fa-filter" onclick="TestSqlFilter();">Test</span>
                </div> 
            </div>
        </div>
        <div>
           
          
        
          

        </div>
   
        <!------->
        <div class="ui-widget mt">
            <div class="ui-widget-header">Test Results</div>
            <div id="TestResults" class="ui-widget-content"></div>
        </div>

    </div>

</div>

<div class="ui-widget mt " style="width:400px;">
        <div class="ui-widget-header">Existing Filters</div>


        <div id="ExistingFilters" class="ui-widget-content">

        </div>
    </div>
